package com.kabuda.zhugehot200;

import java.util.Arrays;
import java.util.HashMap;

/**
 * @author kabuda
 * @date 2025-03-15 20:02
 * @description
 */
public class t1_两数之和 {


    public static void main(String[] args) {
        System.out.println(Arrays.toString(twoSumBySortArr1(new int[]{2, 7, 11, 15}, 9)));
        System.out.println(Arrays.toString(twoSumBySortArr2(new int[]{2, 7, 11, 15}, 9)));

    }


    public static int[] twoSum(int[] nums, int target) {
        int[] result = new int[2];
        HashMap<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            int num = target - nums[i];
            if (map.containsKey(num)) {
                result[1] = i;
                result[0] = map.get(num);
                return result;
            }
            map.put(nums[i], i);

        }

        return result;
    }


    /**
     * 二分查找
     *
     * @param nums   有序的数组
     * @param target
     * @return
     */
    public static int[] twoSumBySortArr1(int[] nums, int target) {
        int[] result = new int[2];
        int left = 0;
        int right = nums.length - 1;
        while (left <= right) {
            if (nums[left] + nums[right] == target) {
                result[0] = left;
                result[1] = right;
                return result;
            } else if (nums[left] + nums[right] < target) {
                left++;
            } else {
                right--;
            }
        }
        return result;
    }

    /**
     * 双指针
     *
     * @param nums   有序的数组
     * @param target
     * @return
     */
    public static int[] twoSumBySortArr2(int[] nums, int target) {
        int[] result = new int[2];
        for (int i = 0; i < nums.length; i++) {
            int left = i;
            int right = nums.length - 1;
            while (left <= right) {
                int mid = left + (right - left) / 2;
                if (nums[mid] + nums[i] == target) {
                    result[0] = i;
                    result[1] = mid;
                    return result;
                } else if (nums[mid] + nums[i] < target) {
                    left = mid + 1;
                } else {
                    right = mid - 1;
                }
            }
        }
        return result;
    }


}
